# -*- coding: utf-8 -*-
# ========================================
# 第三方在线验证码识别
# ========================================

import base64
import requests
from PIL import Image
from io import BytesIO
from hashlib import md5
from sys import version_info


def tujian(username: str, pwd: str, softid: str, path: str) -> dict:
    """
    图鉴验证码识别接口（AI识别）
    网址：http://www.ttshitu.com
    :param username: 用户名
    :param pwd: 密码
    :param softid: 图鉴后台SoftID
    :param path: 图片路径
    :return:
    """
    try:
        im = _remove_transparency(Image.open(path))
        im = im.convert('RGB')
        buffer = BytesIO()
        im.save(buffer, format='JPEG')
        if version_info.major >= 3:
            b64 = str(base64.b64encode(buffer.getvalue()), encoding='utf-8')
        else:
            b64 = str(base64.b64encode(buffer.getvalue()))
        buffer.close()
        data = {'username': username, 'password': pwd, 'softid': softid, 'image': b64}
        r = requests.post('http://api.ttshitu.com/base64', json=data).json()
        if r['success']:
            return r['data']
        else:
            raise Exception(r['message'])
    except Exception as e:
        print(e)
        return {}


def tujian_report_error(username: str, pwd: str, image_id: str) -> dict:
    """
    图鉴验证码识别报错接口
    :param username: 用户名
    :param pwd: 密码
    :param image_id: 请求图片识别返回的图片ID
    :return:
    """
    try:
        data = {
            'username': username,
            'password': pwd,
            'id': image_id
        }
        headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }
        r = requests.post('http://api.ttshitu.com/reporterror.json', data=data, headers=headers)
        return r.json()
    except Exception as e:
        print(e)
        return {}


def chaojiying(username: str, password: str, softid: str, codetype: int, imgpath: str) -> dict:
    """
    超级鹰验证码识别（打码平台识别）
    网址：http://www.chaojiying.com
    :param username: 用户名
    :param password: 用户密码
    :param softid: 软件ID(用户中心 >> 软件ID)
    :param codetype: 题目类型(官方网站>>价格体系) 参考 http://www.chaojiying.com/price.html
    :param imgpath: 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    :return:
    """
    try:
        password = password.encode('utf8')
        password = md5(password).hexdigest()
        data = {
            'codetype': codetype,
            'user': username,
            'pass2': password,
            'softid': softid,
        }
        headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }
        with open(imgpath, 'rb') as f:
            files = {'userfile': ('ccc.jpg', f.read())}
            r = requests.post('http://upload.chaojiying.net/Upload/Processing.php',
                              data=data, files=files, headers=headers)
        return r.json()
    except Exception as e:
        print(e)
        return {}


def chaojiying_report_error(username: str, password: str, softid: str, imgid: str) -> dict:
    """
    超级鹰验证码识别报错接口
    :param username: 用户名
    :param password: 用户密码
    :param softid: 用户中心 >> 软件ID
    :param imgid: 报错题目的图片ID
    :return:
    """
    try:
        password = password.encode('utf8')
        password = md5(password).hexdigest()
        data = {
            'id': imgid,
            'user': username,
            'pass2': password,
            'softid': softid,
        }
        headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=data, headers=headers)
        return r.json()
    except Exception as e:
        print(e)
        return {}


def _remove_transparency(im: Image, bg_colour: tuple = (255, 255, 255)) -> Image:
    """
    去除图片透明背景
    :param im: PIL.Image 对象
    :param bg_colour: 替代透明的颜色值
    :return: PIL.Image
    """
    # Only process if image has transparency (http://stackoverflow.com/a/1963146)
    if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):

        # Need to convert to RGBA if LA format due to a bug in PIL (http://stackoverflow.com/a/1963146)
        alpha = im.convert('RGBA').split()[-1]

        # Create a new background image of our matt color.
        # Must be RGBA because paste requires both images have the same format
        # (http://stackoverflow.com/a/8720632  and  http://stackoverflow.com/a/9459208)
        bg = Image.new('RGBA', im.size, bg_colour + (255,))
        bg.paste(im, mask=alpha)
        return bg

    else:
        return im


if __name__ == '__main__':
    print('MeCaptcha - More Efficient UiBot Extension')

    # code = tujian('', '', '',  '../_temp/sample.png')
    # print(code)
    #
    # code = tujian('', '', '', '../_temp/captcha.jpg')
    # print(code)

    # code = chaojiying('', '', '', 6001, '../_temp/captcha.gif')
    # print(code)
